package com.explore.demo.intercept;

import com.explore.demo.cache.RedisCache;
import com.explore.demo.config.JwtConfig;
import io.jsonwebtoken.Claims;
import org.apache.juli.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;

/**
 * @author gaolainan
 */
@Component
public class TokenInterceptor implements HandlerInterceptor
{

    private static Logger logger= LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws SignatureException
    {
        /** 地址过滤 */
        String uri = request.getRequestURI() ;
        if (uri.contains("/user/login") || uri.contains("/swagger-ui.html")){
            return true ;
        }
        logger.info("进入拦截器 =====> TokenIntercept");


        String token = request.getHeader(jwtConfig.getHeader());
        if (token == null){
            throw new SignatureException("失效请重新登录");
        }
        logger.info("传进来的token ====> "+token);
        Claims claims = null;
        try{
            claims = jwtConfig.getTokenClaim(token);
            if (claims == null || jwtConfig.isTokenExpired(claims.getExpiration())){
                throw new SignatureException(jwtConfig.getHeader() + "失效，请重新登录。");
            }
        }catch (Exception e){
            throw new SignatureException(jwtConfig.getHeader() + "失效，请重新登录。");
        }

        /// request.setAttribute("identityId", claims.getSubject());
        logger.info("展示claims.getSubject 的内容： =====> "+claims.getSubject());
        return true;
    }
}
